#include <assert.h>
#include "includer.h"
using namespace std;

SDL_Surface* initial = NULL;

void setUpScreen(int width, int height) {

	SDL_Init( SDL_INIT_EVERYTHING );

	initial = SDL_SetVideoMode( width, height,32,SDL_SWSURFACE);

	SDL_WM_SetCaption( "Eli", NULL );

}

SDL_Surface* loadImage( std::string filename ) 
{

	SDL_Surface* loadedImage = NULL;

	SDL_Surface* optimizedImage = NULL;

	loadedImage = IMG_Load( filename.c_str() );

	if( loadedImage != NULL )
	{

		optimizedImage = SDL_DisplayFormat( loadedImage );

		Uint32 colorkey = SDL_MapRGB(optimizedImage->format, 100, 255, 200);

		SDL_SetColorKey(optimizedImage, SDL_SRCCOLORKEY, colorkey);

		SDL_FreeSurface( loadedImage );
	}

	return optimizedImage; 
}



void updateSurface(SDL_Surface* updateable){ 
	SDL_Flip(updateable);
}

void clean_up(SDL_Surface* clean) {
	SDL_FreeSurface( clean );
	SDL_Quit();
}

int main (int argc, char* args[]) {
	//TODO replace with main area
	bool quit = false;

	setUpScreen(1280,800);

	SDL_Surface* myImage = loadImage("Image/Eli-Default-Blink/FlumpBlinkSpriteDefault.png");
	SDL_Surface* bg = loadImage("Image/bg.jpg");
	ostringstream convert;
	fps.start();
	update.start();
	FlumpDefault def;
	FrameRate frameObj;
	// only used for debug
	int start_of_previous_frame = 0;
	int start_of_current_frame = fps.get_ticks();

	// used for actual calcs
	int desired_end_of_current_frame = fps.get_ticks();
	
	while(quit == false) {
		start_of_previous_frame = start_of_current_frame;
		start_of_current_frame = fps.get_ticks();

		desired_end_of_current_frame += (1000 / FRAME_RATE);
		while(SDL_PollEvent(&event)) {

			Uint8 *keystates = SDL_GetKeyState( NULL );

			if(keystates[SDLK_END]) {
				quit = true;
			}
			
			def.handleInput(event);
		}

		def.move();
		SDL_FillRect(initial,NULL,0x000000);
		def.show(initial);
		frameObj.applyFrames(update.get_ticks(),start_of_current_frame, start_of_previous_frame, initial);
		frame++;
		
		SDL_Flip(initial);

		if((cap == true) && (fps.get_ticks() < desired_end_of_current_frame))
		{
			SDL_Delay(desired_end_of_current_frame - fps.get_ticks());
//			SDL_Delay( ( 1000 / FRAME_RATE ) - fps.get_ticks() );
		}
		else
		{
			cout<<"We are too slow! " << fps.get_ticks() << " old: " << start_of_previous_frame << " new: " << start_of_current_frame << "DELTA: " << (start_of_current_frame - start_of_previous_frame)<< endl;
			desired_end_of_current_frame = fps.get_ticks();
		}

	}
	update.start();
	frameObj.closeFont();
	clean_up(myImage);
	clean_up(bg);
	return 0;
}

